window.onload = function() {
    init();
}

function init() {
    initCourseList()
}
var initCourseList = (function() {
    var oBtnGroup = document.getElementsByClassName('but-group')[0],
        oBtnItems = document.getElementsByClassName('btn-item'),
        oList = document.getElementsByClassName('js-list')[0],
        oTpl = document.getElementById('J_itemTpl').innerHTML,
        oLoading = document.getElementsByClassName('loading')[0],
        page = 0,
        t = null,
        cache = {};

    function init() {
        getAjaxCourses()
        bindEvent();
    }



    function bindEvent() {
        addEvent(oBtnGroup, 'click', btnClick)
    }

    function btnClick(e) {
        var e = e || window.event,
            tar = e.target || e.srcElement,
            oParent = tar.parentNode,
            className = oParent.className,
            thisIdx = -1;
        if (className === 'btn-item') {
            console.log()
            thisIdx = Array.prototype.indexOf.call(oBtnItems, oParent);
            var len = oBtnItems.length,
                item;
            page = thisIdx;
            // 缓存
            cache[page] ? getCacheCourses() : getAjaxCourses();
            for (var i = 0; i < len; i++) {
                item = oBtnItems[i]
                item.className = 'btn-item';
            }
            oParent.className += ' cur'

        }
    }

    function getAjaxCourses() {
        ajaxReturn({
            url: APIs.getCourses,
            data: {
                page: pagePos
            },
            success: function(data) {
                cache[page] = data;
                oLoading.style.display = 'block';
                t = setTimeout(function() {
                    render(data);
                    oLoading.style.display = 'none';
                }, 500)
            },
            error: function() {
                console.log('获取数据失败');
            }
        })
    }

    function getCacheCourses() {
        var data = cache[page];
        render(data);
    }

    function render(data) {
        var list = '',
            len = data.length,
            item;
        for (var i = 0; i < len; i++) {
            item = data[i];
            list += setTplToHTML(oTpl, regTpl, {
                folder: item.folder,
                classname: item.classname,
                watched: item.watched
            })
        }
        oList.innerHTML = list;
    }
    return function() {
        init()
    }
})();
var APIs = {
    getCourses: 'http://study.lfclass.com/Index/getCourses'
}

function ajaxReturn(opt) {
    $.ajax({
        url: opt.url,
        type: 'POST',
        dataType: 'JSON',
        timeout: 100000,
        success: opt.success,
        error: opt.error
    })
}